<?php

namespace App\Http\Controllers\Frontend\Auth;

use App\Http\Controllers\Frontend\FrontendController;
use App\Http\Requests\Frontend\Auth\LoginRequest;
use App\Http\Resources\Frontend\ApiResource;
use App\Http\Resources\Frontend\UserResource;
use App\Models\User;
use Illuminate\Auth\Events\Attempting;
use Illuminate\Auth\Events\Login;

class AuthController extends FrontendController
{

    public function __construct()
    {
        $this->middleware('auth:' . $this->guard, ['except' => ['login']]);
    }

    public function login(LoginRequest $request)
    {
        $credentials = $request->only(['email', 'password']);
        $remember = $request->post('remember');

        event(new Attempting(
            $this->guard, $credentials, $remember
        ));

        $user = User::where(['email' => $request->post('email')])->first();

        if(!$user) {
            return new ApiResource('邮箱未注册', 401);
        }

        if(!\Hash::check($request->post('password'), $user->password)) {
            event(new Login(
                $this->guard, $user, $remember
            ));
            return new ApiResource('密码错误', 401);
        }
        $token = auth($this->guard)->login($user);

        $user = array_merge($user->toArray(), $this->respondWithToken($token));

        return (new UserResource($user));
    }

    public function logout()
    {
        auth($this->guard)->logout(true);

        return new ApiResource('注销成功');
    }

    public function refresh()
    {
        return new ApiResource('OK', 200, $this->respondWithToken(auth($this->guard)->refresh()));
    }

}
